﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FbKPI.Model;
using FbKPI.Facade;
using System.Web.Script.Serialization;
using System.Collections.ObjectModel;
using System.Web.Script.Services;

namespace FBKPI.Serializer
{
    /// <summary>
    /// Summary description for KPIAchievementSerializer
    /// </summary>
    public class KPIAchievementSerializer : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/json";
            string result = this.GetAllData();
            context.Response.Write(result);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string GetAllData()
        {
            int KPIAssign = Convert.ToInt16(HttpContext.Current.Request.Params["KPIAssign"]);
            int Year = Convert.ToInt16(HttpContext.Current.Request.Params["Year"]);
            int Month = Convert.ToInt16(HttpContext.Current.Request.Params["Month"]);
            int User = Convert.ToInt16(HttpContext.Current.Request.Params["User"]);

            KPIAchievement result = new KPIAchievement();
            KPIAchievementFacade pf = new KPIAchievementFacade();
            IList<KPIAttachment> attachment = new List<KPIAttachment>();
            KPIAttachmentFacade kf = new KPIAttachmentFacade();

            result = pf.GetKPIAchievementDetail(Month, Year, KPIAssign);
            attachment = kf.GetKPIAttachmentByKPIAssign(KPIAssign, Month, Year);

            Employee Verificator = new KPIAssignFacade().GetKPIAssignByID(KPIAssign).Verifier;
            Employee CurrUser = new EmployeeFacade().GetEmployeeByID(User);

            bool isCreator = false;
            if (result != null)
            {
                if (CurrUser.Email == result.CreateBy && result.isLocked)
                    isCreator = true;
            }

            bool isVerificator = false;
            if(Verificator.ID == User)
                isVerificator = true;

            var gridData = new
            {
                result,
                isVerificator,
                isCreator,
                attachment
            };
            var JSONSerializer = new JavaScriptSerializer();
            return JSONSerializer.Serialize(gridData);
        }
    }
}